#include "spi_comm.h"
#include "stm32f4xx_hal.h"

extern SPI_HandleTypeDef hspi1; // SPI1：ARM与FPGA2通信

// SPI初始化：10Mbps（APB2时钟84MHz，分频系数8→10.5Mbps，接近10Mbps）
void SPI_Init_10Mbps(void) {
  hspi1.Instance = SPI1;
  hspi1.Init.Mode = SPI_MODE_MASTER;
  hspi1.Init.Direction = SPI_DIRECTION_2LINES; // 全双工
  hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi1.Init.NSS = SPI_NSS_SOFT;
  hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8; // 84/8=10.5Mbps
  hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi1.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi1) != HAL_OK) {
    Error_Handler();
  }
}

// SPI发送数据（含超时检测）
HAL_StatusTypeDef SPI_Send_Data(uint8_t *pData, uint16_t Size, uint32_t Timeout) {
  return HAL_SPI_Transmit(&hspi1, pData, Size, Timeout);
}

// SPI接收数据（含超时检测）
HAL_StatusTypeDef SPI_Receive_Data(uint8_t *pData, uint16_t Size, uint32_t Timeout) {
  return HAL_SPI_Receive(&hspi1, pData, Size, Timeout);
}